package com.kma.summer2012.client.presenters.header;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.kma.summer2012.client.CrumbsEventBus;
import com.kma.summer2012.client.events.authorization.LoginEvent;
import com.kma.summer2012.client.presenters.Presenter;
import com.kma.summer2012.shared.model.UICrumbsUser;

public class HeaderPresenter implements Presenter {

    public interface Display {
        HasClickHandlers getLogOutButton();

        void setPosition(String position);

        void setName(String name);

        Widget asWidget();
    }

    private final Display display;
    private static UICrumbsUser user;

    public static UICrumbsUser getUser() {
        return user;
    }

    public HeaderPresenter(Display display, UICrumbsUser user) {
        HeaderPresenter.user = user;
        this.display = display;
        this.display.setName(user.getSurnmNmSecondnm());
        this.display.setPosition(user.getPosition());

        bind();
    }

    private void bind() {
        this.display.getLogOutButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                HeaderPresenter.user = null;
                Cookies.removeCookie("user");
                CrumbsEventBus.getInstance().fireEvent(new LoginEvent());
            }
        });
    }

    @Override
    public void go(HasWidgets container) {
        container.clear();
        container.add(display.asWidget());
    }
}
